package com.infinit.easyreader.utils;

import android.content.Context;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * 类：com.infinit.easyreader.utils.NetUtils V[1.0.0]
 * 作用：处理请求的一些的工具方法
 * Created by rzy on 2016/6/2.
 */
public class NetUtils {
    public static volatile NetUtils instance;
    private static RequestQueue mRequestQueue;

    private NetUtils() {
    }

    public static NetUtils getInstance() {
        if (instance == null) {
            synchronized (NetUtils.class) {
                if (instance == null) {
                    instance = new NetUtils();
                }
            }
        }
        return instance;
    }

    /**
     * 添加Request
     *
     * @param context context的实例
     * @param request Volley的Request对象
     * @param tag     TAG，用于标识Request
     */

    public void addRequest(Context context, Request<?> request, String tag) {


        //获取一个RequestQueue
        getRequestQueue(context);
        request.setTag(tag);
        mRequestQueue.add(request);

    }

    public void addRequest(Request<?> request, Context context) {
        getRequestQueue(context).add(request);
    }

    /**
     * 获取一个RequstQueue的实例
     *
     * @param context context实例
     * @return 一个唯一的RequestQueue实例
     */


    public RequestQueue getRequestQueue(Context context) {
        //获取一个RequestQueue
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(context);
        }
        return mRequestQueue;
    }

    /**
     * 取消所有请求
     *
     * @param context context对象
     * @param tag     请求的标识符
     */
    public void cancelAllRequest(Context context, String tag) {
        if (getRequestQueue(context) != null) {
            mRequestQueue.cancelAll(tag);
        }


    }


    /**
     * 转换参数为字符串
     */

    public String urlencode(Map<String, String> data) {
        StringBuilder builder = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            try {
                builder.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return builder.substring(0, builder.length());
    }


}

